package com.nlecloud.bc.service.impl;

import com.nlecloud.bc.controller.dto.UserDTO;
import com.nlecloud.bc.dao.UserDao;
import com.nlecloud.bc.exception.BusinessException;
import com.nlecloud.bc.model.User;
import com.nlecloud.bc.service.IUserService;
import com.nlecloud.bc.service.contract.IUserContractService;
import com.nlecloud.bc.util.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author warrior
 * @description 用户操作服务接口实现
 */
@Service
public class UserService implements IUserService {

    private static final String DEFAULT_AMOUNT = "10000";

    @Resource
    private UserDao userDao;

    @Autowired
    private IUserContractService userContractService;

    @Override
    public String login(String username,String password) {
        //这个用户是否存在数据库
        User user = userDao.findByUsername(username);
        if(user == null){
            throw new BusinessException("用户不存在");
        }

        if(!password.equals(user.getPassword())){
            throw new BusinessException("密码错误");
        }

        String id = user.getId();
        //生成token
        String token = JwtUtil.generateToken(id,username);
        return token;
    }

    @Override
    public void register(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user = userDao.save(user);
        //用户合约设置余额
        userContractService.setBalance(user.getId(),DEFAULT_AMOUNT);
    }

    @Override
    public List<UserDTO> listAllUser() {
        List<User> users = userDao.findAll();
        if(CollectionUtils.isEmpty(users)){
            return Collections.emptyList();
        }
        List<UserDTO> userDTOS = new ArrayList<>(users.size());
        users.stream().forEach(user -> {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(user,userDTO);
            userDTOS.add(userDTO);
        });
        return userDTOS;
    }
}
